import notificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
// import { getBundleName } from './BundleUtil';
import { WantAgent } from '@ohos.wantAgent';
import { pushService } from '@kit.PushKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

/*推送服务*/
export namespace PushKitUtil {

  export function requestEnableNotification(context: common.UIAbilityContext): Promise<boolean> {
    return notificationManager.isNotificationEnabled()
      .then((data: boolean) => {
        if (!data) {
          return notificationManager.requestEnableNotification(context)
            .then(() => true)
        }
        return true; // 如果已启用通知，直接返回 true
      })
      .catch((err: BusinessError) => {
        return false; // 如果检查通知是否启用时发生错误
      });
  }

  export function getToken(): Promise<string> {
    return pushService.getToken()
  }

}

export namespace LocalPushUtil {

  /**
   * 发送新聊天提醒推送
   */
  export function publishNewChatMessage(senderName: string, message: string) {
    wantAgent.getWantAgent(createWantAgentInfo('net.luculent.harmonytemplate')).then((value) => {
      //发送本地通知推送
      publishNotification(value, senderName, message);
    })
  }

  /**
   * 发送本地系统推送
   * @param value WantAgent 对象
   * @param senderName 消息发送方名称
   * @param message 消息内容
   */
  function publishNotification(value: WantAgent, senderName: string, message: string) {
    let noticeRequest: notificationManager.NotificationRequest = {
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: senderName,
          text: message,
          additionalText: '会话消息'
        },
      },
      wantAgent: value,
      notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
      showDeliveryTime: true,
      deliveryTime: new Date().getTime(),
    };
    notificationManager.publish(noticeRequest).catch((error)=>{
      console.log(JSON.stringify(error))
    })
  }

  /**
   * 构造WantAgentInfo
   * @param bundleName 包名
   * @returns WantAgentInfo
   */
  function createWantAgentInfo(bundleName: string): wantAgent.WantAgentInfo {
    const wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [{
        deviceId: '',
        bundleName: bundleName,
        abilityName: 'EntryAbility',
        action: '',
        entities: [],
        uri: '',
        parameters: {}
      }],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    }
    return wantAgentInfo;
  }
}
